<script setup lang="ts">
import type { ValidateErrorEntity } from 'ant-design-vue/es/form/interface';
import type { RuleObject } from 'ant-design-vue/lib/form';

import type { SysDeptResp } from '#/type/sys_dept';
import type { SysPostResp } from '#/type/sys_post';
import type { SysRoleResp } from '#/type/sys_role';
import type { SysTenantResp } from '#/type/sys_tenant';
import type { SysUserResp } from '#/type/sys_user';

import { computed, ref, watch } from 'vue';
import type { PropType } from 'vue';

import {
  Col,
  Divider,
  Form,
  FormItem,
  Input,
  InputNumber,
  message,
  Modal,
  RadioGroup,
  Row,
  Select,
  SelectOption,
  Switch,
  TreeSelect,
} from 'ant-design-vue';

import { antTreeHandler } from '#/utils/antTools';

const props = defineProps({
  open: {
    type: Boolean,
    default: false,
  },
  data: {
    type: Object as PropType<SysUserResp> | undefined,
    default: () => {},
  },
  tenantList: {
    type: Array as PropType<Array<SysTenantResp>>,
    default: () => [],
  },
  deptList: {
    type: Array as PropType<Array<SysDeptResp>>,
    default: () => [],
  },
  postList: {
    type: Array as PropType<Array<SysPostResp>>,
    default: () => [],
  },
  roleList: {
    type: Array as PropType<Array<SysRoleResp>>,
    default: () => [],
  },
});

const emit = defineEmits(['ok', 'cancel']);
const formRef = ref();
const formRules: { [k: string]: RuleObject | RuleObject[] } = {
  user_name: [
    {
      type: 'string',
      required: true,
      message: '请输入名称',
      trigger: 'blur',
    },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' },
  ],
  nick_name: [
    {
      type: 'string',
      required: true,
      message: '请输入编码',
      trigger: 'blur',
    },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' },
  ],
  tenant_id: [{ required: true, message: '请选择租户', trigger: 'change' }],
  dept_ids: [
    { required: true, message: '请选择部门', trigger: 'change', type: 'array' },
  ],
  role_ids: [
    { required: true, message: '请选择角色', trigger: 'change', type: 'array' },
  ],
};
// 创建本地数据副本
const localData = ref<SysUserResp>({ ...props.data });
// 在 props.data 变化时更新本地数据
watch(
  () => props.data,
  (newData) => {
    localData.value = { ...newData } as SysUserResp;
  },
  { deep: true },
);

const deptTreeData = computed(() => {
  const list = props.deptList;
  if (!list || !Array.isArray(list) || list.length === 0) return [];
  return antTreeHandler(list, 'dept_id', 'dept_name', 'parent_id');
});
const sexOptions = [
  { label: '男', value: 1 },
  { label: '女', value: 2 },
];
const modalSubmit = () => {
  formRef.value
    .validate()
    .then(() => {
      emit('ok', localData.value);
    })
    .catch((_: ValidateErrorEntity) => {
      message.error({
        content: '请检查表单填写是否正确',
        duration: 1,
      });
    });
};
</script>

<template>
  <Modal
    :mask-closable="false"
    :open="open"
    :style="{ maxWidth: '50%', width: '50%' }"
    :title="localData ? '编辑' : '新建'"
    @cancel="emit('cancel')"
    @ok="modalSubmit"
  >
    <Divider />
    <Form
      ref="formRef"
      :label-col="{ span: 6 }"
      :model="localData"
      :rules="formRules"
      :wrapper-col="{ span: 18 }"
      layout="horizontal"
    >
      <Row :gutter="16">
        <Col :span="12">
          <FormItem label="用户名" name="user_name">
            <Input
              v-model:value="localData.user_name"
              placeholder="请输入用户名"
            />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem label="昵称" name="nick_name">
            <Input
              v-model:value="localData.nick_name"
              placeholder="请输入昵称"
            />
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :span="12">
          <FormItem label="租户" name="tenant_id">
            <Select
              v-model:value="localData.tenant_id"
              placeholder="请选择租户"
            >
              <SelectOption
                v-for="tenant in tenantList"
                :key="tenant.tenant_id"
                :value="tenant.tenant_id"
              >
                {{ tenant.org_name }}
              </SelectOption>
            </Select>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem label="角色" name="role_ids">
            <Select
              v-model:value="localData.role_ids"
              mode="multiple"
              placeholder="请选择角色"
            >
              <SelectOption
                v-for="role in roleList"
                :key="role.role_id"
                :value="role.role_id"
              >
                {{ role.role_name }}
              </SelectOption>
            </Select>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :span="12">
          <FormItem label="部门" name="dept_ids">
            <TreeSelect
              v-model:value="localData.dept_ids"
              :tree-data="deptTreeData"
              multiple
              placeholder="请选择部门"
            />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem label="岗位" name="post_ids">
            <Select
              v-model:value="localData.post_ids"
              mode="multiple"
              placeholder="请输入岗位"
            >
              <SelectOption
                v-for="post in postList"
                :key="post.post_id"
                :value="post.post_id"
              >
                {{ post.post_name }}
              </SelectOption>
            </Select>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :span="12">
          <FormItem label="手机号" name="phone">
            <Input v-model:value="localData.phone" placeholder="请输入手机号" />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem label="邮箱" name="email">
            <Input v-model:value="localData.email" placeholder="请输入邮箱" />
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :span="8">
          <FormItem label="性别" name="sex">
            <RadioGroup v-model:value="localData.sex" :options="sexOptions" />
          </FormItem>
        </Col>
        <Col :span="8">
          <FormItem label="状态" name="status">
            <Switch
              v-model:checked="localData.status"
              :checked-value="1"
              :un-checked-value="0"
              checked-children="启用"
              un-checked-children="禁用"
            />
          </FormItem>
        </Col>
        <Col :span="8">
          <FormItem label="排序" name="sort">
            <InputNumber
              v-model:value="localData.sort"
              placeholder="请输入排序"
            />
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :span="24">
          <FormItem :label-col="{ span: 2 }" label="备注" name="remark">
            <Input.TextArea
              v-model:value="localData.remark"
              :rows="2"
              placeholder="请输入备注"
            />
          </FormItem>
        </Col>
      </Row>
    </Form>
    <Divider />
  </Modal>
</template>

<style scoped></style>
